import { useEffect, useState } from "react";
import { useRouter } from "next/router";

export default function PermissionDetails() {
  const router = useRouter();
  const { id } = router.query;
  const [permission, setPermission] = useState(null);
  const [name, setName] = useState("");

  useEffect(() => {
    if (id) {
      const fetchPermission = async () => {
        const res = await fetch(`/api/permissions?id=${id}`);
        const data = await res.json();
        // const data = list[0] || {}
        setPermission(data);
        setName(data.name);
      };
      fetchPermission();
    }
  }, [id]);

  const handleUpdate = async (e) => {
    e.preventDefault();
    const res = await fetch(`/api/permissions?id=${id}`, {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ name }),
    });
    if (res.ok) {
      router.push("/permissions");
    }
  };

  if (!permission) return <div>加载中...</div>;

  return (
    <form onSubmit={handleUpdate} className="container mx-auto">
      <h1 className="text-2xl font-bold my-4">编辑权限</h1>
      <label>权限名称</label>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        className="border border-gray-300 p-2 w-full mb-4"
        required
      />
      <button type="submit" className="bg-blue-500 text-white p-2 rounded">
        更新
      </button>
    </form>
  );
}
